package com.zyl.pagergallerymoredemo_java.viewModel;

import android.app.Application;
import android.util.Log;

import androidx.annotation.NonNull;
import androidx.lifecycle.AndroidViewModel;
import androidx.lifecycle.LiveData;
import androidx.lifecycle.MutableLiveData;

import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.google.gson.Gson;
import com.zyl.pagergallerymoredemo_java.pojo.Pixabay;
import com.zyl.pagergallerymoredemo_java.volley.VolleyUtils;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Random;

public class GalleryViewModel extends AndroidViewModel {

    public static final int DATA_STATUS_CAN_LOAD_MODE = 0;//加载
    public static final int DATA_STATUS_NO_MODE = 1;//数据加载完毕
    public static final int DATA_STATUS_NETWORK_ERROR = 2;//网络异常

    private MutableLiveData<Integer> statusLiveData = new MutableLiveData<>();//存储状态

    public LiveData<Integer> getStatusLiveData() {
        return statusLiveData;
    }

    public boolean needToScrollToTop = true; //回到顶部
    private int perPage = 100; //每页100个图片
    String[] keyWorks = {"usa", "chain", "uk", "dog", "load", "sky"};
//    private String keyWork = keyWorks[new Random().nextInt(keyWorks.length)];

    private int currentPage = 1;//当前页码
    private int totalPage = 1;//总页数
    private String currentKey = "cat";//当前关键词
    private boolean isNewQuery = true; //是否是新请求
    private boolean isLoading = false; //是否在加载中


    {
        resetQuery();
    }

    public void resetQuery() {
        currentPage = 1;
        totalPage = 1;
        currentKey = keyWorks[new Random().nextInt(keyWorks.length)];
        isNewQuery = true;
        needToScrollToTop = true;
        fetchData();
    }

    public GalleryViewModel(@NonNull Application application) {
        super(application);
    }

    private MutableLiveData<List<Pixabay.PhotoItem>> listLiveData = new MutableLiveData<>();

    public LiveData<List<Pixabay.PhotoItem>> getListLiveData() {
        return listLiveData;
    }

    public void fetchData() {
        if (isLoading) return; //加载中，不可以加载其他
        if (currentPage > totalPage) {//数据加载完毕
            statusLiveData.postValue(DATA_STATUS_NO_MODE);
            return;
        }
        isLoading = true; //加载中

        StringRequest stringRequest = new StringRequest(
                Request.Method.GET,
                getUrl(),
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        Pixabay pixabay = new Gson().fromJson(response, Pixabay.class);
                        totalPage = (int) Math.ceil((double) pixabay.getTotalHits() / perPage);
                        if (isNewQuery) {//重新加载
                            listLiveData.postValue(pixabay.getHits());
                        } else {
                            //将前面的数据和现在的一起放到LiveData中
                            ArrayList<Pixabay.PhotoItem> arrayList = new ArrayList<>();
                            arrayList.addAll(listLiveData.getValue());
                            arrayList.addAll(pixabay.getHits());
                            listLiveData.postValue(arrayList);
                        }

                        statusLiveData.postValue(DATA_STATUS_CAN_LOAD_MODE); //还可以加载图片
                        isLoading = false; //没有在加载中了
                        isNewQuery = false;//不是重新加载
                        currentPage++;

                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        statusLiveData.postValue(DATA_STATUS_NETWORK_ERROR); //网络错误
                        Log.d("myTAG", "onErrorResponse: JSON加载失败", error);
                    }
                }
        );

        VolleyUtils.getInstance(getApplication()).getRequestQueue().add(stringRequest);

    }


    private String getUrl() {
        return "https://pixabay.com/api/?key=20367884-4ff0b66c3d8b80b87f646de62&q=" + currentKey + "&per_page=" + perPage + "&page=" + currentPage;
    }


}
